package com.neo.task;

import com.alibaba.fastjson.JSONObject;
import com.neo.utils.O2OJSON;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * Created by yanhao on 2017/12/11.
 */
@Service
public class CreateHttp {
    /**
     *
     */



    // 妙兜测试接口
    public static final String POST_URL = "http://121.40.204.191:8180/mdserver/service/installLock";

    /**
     * 接口调用 GET
     */
    public static void httpURLConectionGET(String GET_URL) {
        try {
            URL url = new URL(GET_URL);    //把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            //addRequestProperty添加相同的key不会覆盖，如果相同，内容会以{name1,name2}
            //connection.addRequestProperty("from", "sfzh");  //来源哪个系统
            //setRequestProperty添加相同的key会覆盖value信息
            //setRequestProperty方法，如果key存在，则覆盖；不存在，直接添加。
            //addRequestProperty方法，不管key存在不存在，直接添加。
            //connection.setRequestProperty("user", "user");  //访问申请用户

            InetAddress address = InetAddress.getLocalHost();
            //TODO 模拟ip
            //randIP();
            String ip;
            ip=address.getHostAddress();//获得本机IP
            System.out.println("本机ip :"+ip);
            ip = randIP();
            System.out.println("执行ip :"+ip);
            connection.setRequestProperty("ip",ip);  //请求来源IP
            //connection.setRequestProperty("encry", "00000");

            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.691.400 QQBrowser/9.0.2524.400");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4");
            // 设置文件类型:

            Integer[] ids ={195,196,197,198,199,200};
            Random random = new Random();
            int num = random.nextInt(ids.length);
            Integer id = ids[num];

            /**

             PHPSESSID=ec308a147a8a9f91192d0375cb51b5bs; token_189=czosNewttZ44fMTk2ZwweOTVmrwrezIjs%2D; wecha_id_189=czunOdfdierzVysdMwaWwfSVwe8NpOerewwNklFdfdreXRrwy3221


             */


            connection.setRequestProperty("Cookie","PHPSESSID=ec11a147a8a9f9156d0375cb51b5bs; " +
                    "token_"+id +"=czosNewttZ44fMTeOTV"+id+"rezIjs%2D; " +
                    "wecha_id_"+id+"=czunOdfdierzVysdMWwlST8NpOUIwNklFdfdreXRrwy3"+id);
           // connection.setRequestProperty("Cookie","PHPSESSID=ec308a147a8a9f91192d0375cb51b5bs; token_189=czosNewttZ44fMTk2ZwweOTVmrwrezIjs%2D; wecha_id_189=czunOdfdierzVysdMwaWwfSVwe8NpOerewwNklFdfdreXRrwy3221");



            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
    }

    /**
     * 接口调用  POST
     */
    public static void httpURLConnectionPOST () {
        try {
            //传递参数
            O2OJSON json = new O2OJSON();
            String phone = getRandomPhone();
            json.put("phone",phone);
            json.put("sourceType",0);
            json.put("type","register");
            json.put("verification","");
            json.put("smsCode","");
            json.put("token","");
            System.out.println("发送短信手机号:"+phone);
            String param = JSONObject.toJSONString(json);
            System.out.println(param);
            final String post_url = "https://m.yaoqianhua.com/yaoqianhua-gateway/authenticationService/getSMSCode";
            URL url = new URL(post_url);
            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)
            // 此时cnnection只是为一个连接对象,待连接中
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);
            // 设置连接输入流为true
            connection.setDoInput(true);
            // 设置请求方式为post
            connection.setRequestMethod("POST");
            // post请求缓存设为false
            connection.setUseCaches(false);
            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);
            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
            // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】
            //addRequestProperty添加相同的key不会覆盖，如果相同，内容会以{name1,name2}
            connection.addRequestProperty("Content-Type", "application/json");  //来源哪个系统
            //setRequestProperty添加相同的key会覆盖value信息
            //setRequestProperty方法，如果key存在，则覆盖；不存在，直接添加。
            //addRequestProperty方法，不管key存在不存在，直接添加。
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");  //访问申请用户
           /* InetAddress address = InetAddress.getLocalHost();
            String ip=address.getHostAddress();//获得本机IP
            connection.setRequestProperty("ip",ip);  //请求来源IP*/
            String ip;
            InetAddress address = InetAddress.getLocalHost();
            ip=address.getHostAddress();//获得本机IP
            System.out.println("本机ip :"+ip);
            ip = randIP();
            System.out.println("执行ip :"+ip);
            connection.setRequestProperty("ip",ip);  //请求来源IP
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36");
            connection.setRequestProperty("Cookie", "gdxidpyhxdE=v3b8DufVROvivALucjbbMMDf5UD6SOKkwGRENyhMHbL97hbyn%5C%5CqTlDdZeRCAwKkYE0aO2IJ8bVzl9SROWh4xhi%5CBGgG4ujxi5MrQB8SWmlU%5CHz%2FdlYQMN3GR9Pf%5CIDTfmtkT1rta93DIQxEHQj5rY1nYQ%2FAL7yR3A%2B%5ClS02bqCPLjOz%3A1513069450643; _9755xjdesxxd_=32; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22160009a130c97e-07fc42a7810504-474f0820-2073600-160009a130d915%22%2C%22%24device_id%22%3A%22160009a130c97e-07fc42a7810504-474f0820-2073600-160009a130d915%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22%22%2C%22%24latest_referrer_host%22%3A%2%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_utm_source%22%3A%2212JZ_fenghuob%22%7D%7D");
            connection.setRequestProperty("device_id", "c6be766c348c53a6669d3bca74ffdaa7");
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();
            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444

          /*  String parm ="username=zhagnsan&password=0000";
            System.out.println("传递参数："+parm);*/
            // 将参数输出到连接
            dataout.writeBytes(param);
            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
            System.out.println(connection.getResponseCode());
            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                //sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String randIP() {

        Random random = new Random(System.currentTimeMillis());
        return (random.nextInt(255) + 1) + "." + (random.nextInt(255) + 1)
                + "." + (random.nextInt(255) + 1) + "."
                + (random.nextInt(255) + 1);
    }

    private static String getRandomPhone() {
        String[] num = {"13","15","18","17"};
        Random random = new Random();
        int nums = random.nextInt(num.length);
        String phs = num[nums];
        Double randoms = Math.random();
        return (phs+randoms.toString().substring(2, 11));
    }

    public static void main(String[] args) throws UnknownHostException {

        Integer[] ids ={195,196,197,198,199,200};
        Random random = new Random();
        int num = random.nextInt(ids.length);
        Integer id = ids[num];
        String GET_URL = "http://7zhongzui.com//Home/index.php?m=Index&a=vote&vid=2167&id="+id+"&tp=HTTP/1.1";
        httpURLConectionGET(GET_URL);
        //httpURLConnectionPOST();

       /* for (int i=0 ; i<50;i++){
            System.out.println(randIP());;
        }*/
    }
}
